const axios = require('axios')
const qs = require('qs')
const Cookie = require('./Cookie')
const writeXlsx = require('./writeXlsx')

const generatePageSessionId = require('./generatePageSessionId')

const getHeader = (obj) => {
  return {
    authority: 'my.cbg.163.com',
    method: 'POST',
    path: '/cgi/api/get_equip_detail?client_type=h5',
    scheme: 'https',
    Accept: 'application/json, text/javascript, */*; q=0.01',
    'Accept-Encoding': 'gzip, deflate, br, zstd',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cbg-Safe-Code': 'PYiyX34J',
    'Content-Length': '259',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    Cookie: Cookie(),
    Origin: 'https://my.cbg.163.com',
    Priority: 'u=1, i',
    Referer: `https://my.cbg.163.com/cgi/mweb/equip/${obj.serverid}/${obj.game_ordersn}?view_loc=search_cond%7Ctag_key%3A%7B%22is_from_ad_reco%22%3A%200,%20%22tag%22%3A%20%22din_ltr_base%22%7D&reco_request_id=1719469908894ciLt1&tag=din_ltr_base`,
    'Sec-Ch-Ua': '"Not/A)Brand";v="8", "Chromium";v="126", "Google Chrome";v="126"',
    'Sec-Ch-Ua-Mobile': '?0',
    'Sec-Ch-Ua-Platform': 'macOS',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest'
  }
}

const getDetails = async (obj) => {
  const url = 'https://my.cbg.163.com/cgi/api/get_equip_detail?client_type=h5'
  const form = {
    serverid: obj.serverid,
    ordersn: obj.game_ordersn,
    h5_device: 'other',
    app_client: 'other',
    view_loc: 'search_cond|tag_key:{"is_from_ad_reco": 0, "tag": "din_ltr_base"}',
    exter: 'www.baidu.com',
    page_session_id: generatePageSessionId()
  }
  try {
    const response = await axios.post(url, qs.stringify(form), {
      headers: getHeader(obj)
    })

    const result = await response.data

    writeXlsx(result)

    // console.log(Object.keys(JSON.parse(result.equip.equip_desc)))

    // console.log(JSON.parse(result.equip.equip_desc).mount.mount_list[0])
  } catch (error) {
    console.error('Error:', error.response ? error.response.data : error.message)
  }
}

module.exports = getDetails
